package com.pmcc.cj.service;


import com.pmcc.cj.entity.*;
import com.pmcc.cj.entity.vo.OrderDetailVo;
import com.pmcc.cj.repository.*;
import com.pmcc.cj.service.threads.MyThreadOrder;
import com.pmcc.cj.service.threads.MyThreadRobot;
import com.pmcc.core.repository.SmsRecordRepository;
import com.pmcc.utils.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.*;

@Transactional
@Service
public class CjWechatService {

    public static final String SPBILL_CREATE_IP = "182.92.124.34";
    public static final String NOTIFY_URL = "http://yun.yunfangbian.com/api/v1/app/notify.json";
    public static final String TRADE_TYPE_APP = "APP"; 

    @Autowired
    CjCustomerRepository cjCustomerRepository;
    @Autowired
    CjOrderIndexRepository cjOrderIndexRepository;
    @Autowired
    CjCountyVillageRepository cjCountyVillageRepository;
    @Autowired
    CjOrderRepository cjOrderRepository;
    @Autowired
    CjOrderDetailRepository cjOrderDetailRepository;
    @Autowired
    CjTaskRepository cjTaskRepository;
    @Autowired
    CjCommodityYunRepository yunRepository;
    @Autowired
   CjCommodityYunDetailRepository detailRepository;
    @Autowired
    SmsRecordRepository smsRecordRepository;
    @Autowired
    CjMoneyRecordRepository cjMoneyRecordRepository;
    @Autowired
    CjShoppingCartRepository cjShoppingCartRepository;
    @Autowired
    CjPositionRepository positionRepository;
    @Autowired
    CjShoppingCartDetailRepository cjShoppingCartDetailRepository;
    @Autowired
    AttackErrorRepository attackErrorRepository;
    @Autowired
    CjPositionRepository cjPositionRepository;
    /**
     * 微信支付
     *
     * @param userId
     * @param total_fee（分）
     * @param body         商品描述
     * @return
     * @throws Exception
     */
    public Map<String, String> dounifiedOrder(String userId, String total_fee, String body,String description) throws Exception {
        System.out.println("*********************************************************");
        System.out.println(description);
        String attach = "";
        WxMD5Util md5Util = new WxMD5Util();
        Map<String, String> returnMap = new HashMap<>();
        WXConfigUtil config = new WXConfigUtil();
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        //生成商户订单号，不可重复
        String out_trade_no =  UUIDGenerator.getUUID();

        data.put("appid", config.getAppID());
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", WXPayUtil.generateNonceStr());
        data.put("body", body);
        data.put("out_trade_no", out_trade_no);
        data.put("total_fee", total_fee);
        //自己的服务器IP地址
        data.put("spbill_create_ip", SPBILL_CREATE_IP);
        //异步通知地址（请注意必须是外网）
        data.put("notify_url", NOTIFY_URL);
        //交易类型
        data.put("trade_type", TRADE_TYPE_APP);
        //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        //data.put("attach", attach);
        String sign1 = md5Util.getSign(data);
        data.put("sign", sign1);
        CjCustomer customer = cjCustomerRepository.findOne(userId);
        CjOrderIndex orderIndex=new CjOrderIndex();
        cjOrderIndexRepository.saveAndFlush(orderIndex);
        attach = "{\"order_id\":\"" + orderIndex.getId() + "\",\"customer_id\":\"" + userId +"\",\"pay_flag\":\"" + customer.getPayFlag() + "\"}";
        data.put("attach", attach);
        try {
            //使用官方API请求预付订单
            Map<String, String> response = wxpay.unifiedOrder(data);
            System.out.println(response);
            String returnCode = response.get("return_code");    //获取返回码
            long time = DateUtil.getTimeStamp();
            //若返回码为SUCCESS，则会返回一个result_code,再对该result_code进行判断
            if (returnCode.equals("SUCCESS")) {//主要返回以下5个参数
                String resultCode = response.get("result_code");
                returnMap.put("appid", response.get("appid"));
                returnMap.put("mch_id", response.get("mch_id"));
                returnMap.put("nonce_str", response.get("nonce_str"));
                returnMap.put("result_code", resultCode);
                returnMap.put("timeStamp", String.valueOf(time));
                if ("SUCCESS".equals(resultCode)) {//resultCode 为SUCCESS，才会返回prepay_id和trade_type
                    //获取预支付交易回话标志
                    returnMap.put("trade_type", response.get("trade_type"));
                    returnMap.put("prepay_id", response.get("prepay_id"));
                    returnMap.put("out_trade_no", out_trade_no);
                    //二次签名
                    Map<String, String> sinMap = new HashMap<>();
                    sinMap.put("appid", response.get("appid"));
                    sinMap.put("partnerid", response.get("mch_id"));
                    sinMap.put("prepayid", response.get("prepay_id"));
                    sinMap.put("noncestr", response.get("nonce_str"));
                    sinMap.put("timestamp", String.valueOf(time));
                    sinMap.put("package", "Sign=WXPay");
                    String sign2 = md5Util.getSign(sinMap);
                    returnMap.put("sign", sign2);
                    JSONObject jsonObject = JSONObject.fromObject(description);
                    //生成订单
                    orderIndex.setPayId(out_trade_no);
                    orderIndex.setWxpayId(response.get("prepay_id"));
                    orderIndex.setCreateTime(new Date());
                    orderIndex.setPayStatus(0);
                    orderIndex.setEmployeeId(customer.getId());
                    orderIndex.setName(customer.getWechatName());
                    orderIndex.setCellphone(customer.getCellphone());
                    orderIndex.setMoney(new BigDecimal(jsonObject.getString("allmoney")).divide(new BigDecimal(100)));
                    orderIndex.setAppId(sinMap.get("appid"));
                    orderIndex.setMchId(returnMap.get("mch_id"));
                    orderIndex.setPrepayId(sinMap.get("prepayid"));
                    orderIndex.setNonceStr(sinMap.get("noncestr"));
                    orderIndex.setTimeStamp(sinMap.get("timestamp"));
                    orderIndex.setSign(returnMap.get("sign"));
                    orderIndex.setOutTradeNo(returnMap.get("out_trade_no"));
                    cjOrderIndexRepository.saveAndFlush(orderIndex);


                    //开启一个线程，设置支付时间为30分钟，超过30分钟还未支付，则该订单取消
                    Thread thread = new Thread(new MyThreadOrder(cjOrderIndexRepository,orderIndex.getId(),cjOrderRepository));
                    thread.start();


                    //从body 里面取数据 {'totalmoney':80.00,genre:1(1代表飞防，0代表商城),isSaleRule:0(0代表未使用满减,1代表使用满减),isNormal:0 (0标准，1非标准规格)
                    //       yun:id(传入套餐id),yunPrice:10(套餐单价),yunNum:8(套餐亩数),detail:{['id':'商品id','dose':'规格','name':'商品名称']}}
                   // cjOrder.setGenre();
                    JSONArray array=JSONArray.fromObject(jsonObject.getString("yunDetail"));
                        for(int i=0;i<array.size();i++){
                            CjOrder cjOrder = new CjOrder();
                            cjOrder.setOrderIndexId(orderIndex.getId());
                            cjOrder.setGenre(Integer.parseInt(array.getJSONObject(i).getString("genre")));
                            cjOrder.setMoney(BigDecimal.valueOf(Double.parseDouble(array.getJSONObject(i).getString("totalmoney"))/100.00));
                            cjOrder.setIsSaleRule(Integer.parseInt(array.getJSONObject(i).getString("isSaleRule")));
                            cjOrder.setIsYun(Integer.parseInt(array.getJSONObject(i).getString("genre")));
                            cjOrder.setIsNormal(Integer.parseInt(array.getJSONObject(i).getString("isNormal")));
                            cjOrder.setOrderStatus(1);
                            cjOrder.setEmployeeId(customer.getId());
                            cjOrder.setYunId(array.getJSONObject(i).getString("yun"));
                            cjOrder.setPayStatus(0);

                            //删除购物车数据
                            Object shopCarId= array.getJSONObject(i).get("shopId");
                            if(shopCarId != null){
                                List<CjShoppingCartDetail>  list=cjShoppingCartDetailRepository.findByShoppingCartId(shopCarId.toString());
                                if(list != null && list.size()>0){
                                    for(CjShoppingCartDetail shoppingCartDetail:list){
                                        cjShoppingCartDetailRepository.delete(shoppingCartDetail);
                                    }
                                }
                                cjShoppingCartRepository.delete(shopCarId.toString());
                            }

                            //不需要邮寄
                            cjOrder.setIsMail(0);
                            //放套餐名称
                           CjCommodityYun yun= yunRepository.findById(array.getJSONObject(i).getString("yun"));
                            cjOrder.setYunName(yun.getName());
                            //订单详细地址
                            cjOrder.setAddress(customer.getProvince()+customer.getCity()+customer.getCounty()+customer.getTownship()+customer.getVillage()+customer.getAddress());
                            //联系人
                            cjOrder.setLinkman(customer.getWechatName());
                            //手机号
                            cjOrder.setCellphone(customer.getCellphone());
                            //时间
                            cjOrder.setCreateTime(new Date());



                            cjOrder.setCommodityCount(Integer.parseInt(array.getJSONObject(i).getString("yunNum")));
                            cjOrder.setPrice(BigDecimal.valueOf(Double.parseDouble(array.getJSONObject(i).getString("yunPrice"))));
                            //零售商id未处理？？？？？？？？？？？绑定与村名称
                            //获取当前登录人最后的一条地址信息记录
                            List<CjPosition> list=positionRepository.findByCustomerIdOrderByCreateTimeDesc(userId);
                            //零售商需要绑定县，防止同名
                            CjCountyVillage cjCountyVillage=cjCountyVillageRepository.findByFettleAndAddressAndCounty(0,list.get(0).getStreet(),list.get(0).getCounty());
                            if(cjCountyVillage !=null){
                                cjOrder.setRetailerId(cjCountyVillage.getCustomerId());
                            }

                            cjOrder = cjOrderRepository.saveAndFlush(cjOrder);
                            List<OrderDetailVo> ls = (List<OrderDetailVo>) JSONArray.toCollection(JSONArray.fromObject(array.getJSONObject(i).getString("detail")),OrderDetailVo.class);
                            if(ls != null && ls.size()>0){
                                for(OrderDetailVo detailVo: ls){
                                    CjOrderDetail orderDetail = new CjOrderDetail();
                                    orderDetail.setOrderId(cjOrder.getId());
                                    orderDetail.setCommodityId(detailVo.getId());
                                    orderDetail.setNumber(Integer.parseInt(detailVo.getDose()));
                                    orderDetail.setName(detailVo.getName());
                                    orderDetail.setFettle(cjOrder.getGenre());
                                    cjOrderDetailRepository.saveAndFlush(orderDetail);
                                }
                            }
                        }

                } else {
                    //此时返回没有预付订单的数据
                    return returnMap;
                }
            } else {
                return returnMap;
            }
        } catch (Exception e) {
            System.out.println(e);
            //系统等其他错误的时候
        }
        return returnMap;
    }

    /**
     * 微信支付官方回调地址
     * notifyMap=
     * {transaction_id=4200000690202009245626120950,
     * nonce_str=636046272521484894fd74017b49906c,
     * bank_type=OTHERS,
     * openid=oOz7F56Y-jY8zBDXF-Q9Y-8mXzXs,
     * sign=7A2670A276A3E74DCB8FA5D8CDC6D77C,
     * fee_type=CNY, mch_id=1602829892,
     * cash_fee=1, out_trade_no=wxpay1600916601257,
     * appid=wx8847f7b4611fa7d5, total_fee=1, trade_type=APP,
     * result_code=SUCCESS, attach={"user_id":"zhulongfei-ceshi-pay"},
     * time_end=20200924110331, is_subscribe=N, return_code=SUCCESS}
     *
     * @param request
     * @param response
     * //该方法微信会调用多次
     * @return
     */
    public synchronized String payBack(HttpServletRequest request, HttpServletResponse response) {
        String notifyData = "";
        WxMD5Util md5Util = new WxMD5Util();
        try {
            InputStream inputStream = request.getInputStream();
            //将InputStream转换成xmlString
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            notifyData = sb.toString();
        } catch (Exception e) {
            System.out.println("微信手机支付失败:" + e.getMessage());
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            return result;
        }

        WXConfigUtil config = null;
        try {
            config = new WXConfigUtil();
        } catch (Exception e) {
            e.printStackTrace();
        }
        WXPay wxpay = new WXPay(config);
        String xmlBack = "";
        Map<String, String> notifyMap = null;
        try {
            notifyMap = WXPayUtil.xmlToMap(notifyData);         // 调用官方SDK转换成map类型数据
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {//验证签名是否有效，有效则进一步处理
                String return_code = notifyMap.get("return_code");//状态
                String out_trade_no = notifyMap.get("out_trade_no");//商户订单号
                if (return_code.equals("SUCCESS")) {
                    //二次签名校验
                    if (md5Util.getSign(notifyMap).equals(notifyMap.get("sign"))) {
                        if (out_trade_no != null) {
                            // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户的订单状态从退款改成支付成功
                            // 注意特殊情况：微信服务端同样的通知可能会多次发送给商户系统，所以数据持久化之前需要检查是否已经处理过了，处理了直接返回成功标志
                            //业务数据持久化
                            System.err.println("支付成功");
                            System.out.println(notifyMap.toString());
                            //修改为成功状态
                            String attach = notifyMap.get("attach");
                            JSONObject jsonObject = JSONObject.fromObject(attach);
                            String orderIndexId = jsonObject.getString("order_id");

                            //重新请求一次微信确认支付成功
                            Map<String, String> data = new HashMap<>();
                            Map<String, String> result = new HashMap<>();
                            data.put("appid", config.getAppID());
                            data.put("mch_id", config.getMchID());
                            data.put("nonce_str", WXPayUtil.generateNonceStr());
                            data.put("out_trade_no", out_trade_no);
                            String sign1 = md5Util.getSign(data);
                            data.put("sign", sign1);
                            result = wxpay.orderQuery(data);
                            if ("SUCCESS".equals(result.get("return_code")) && "SUCCESS".equals(result.get("result_code"))) {
                                if("SUCCESS".equals(result.get("trade_state"))){
                                    this.orderSuccess(orderIndexId,result.get("total_fee"));
                                }
                            }


                            xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                        } else {
                            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                        }
                    } else {
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[签名二次验证失败]]></return_msg>" + "</xml> ";
                    }
                }
                return xmlBack;
            } else {
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
                //失败的数据要不要存储？
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return xmlBack;
            }
        } catch (Exception e) {
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        return xmlBack;
    }

    /**
     * 订单查询
     *
     * @param outTradeNo 订单号(并非一级订单号id)
     * @return
     */
    public Map<String, String> orderQuery(String outTradeNo,String orderIndexId) {
        ResultBean resultBean = new ResultBean();
        WxMD5Util md5Util = new WxMD5Util();
        Map<String, String> data = new HashMap<>();
        WXConfigUtil config = null;
        Map<String, String> returnMap = new HashedMap();
        try {
            config = new WXConfigUtil();
            WXPay wxpay = new WXPay(config);
            Map<String, String> result = new HashMap<>();
            data.put("appid", config.getAppID());
            data.put("mch_id", config.getMchID());
            data.put("nonce_str", WXPayUtil.generateNonceStr());
            data.put("out_trade_no", outTradeNo);
            String sign1 = md5Util.getSign(data);
            data.put("sign", sign1);
            result = wxpay.orderQuery(data);
            if ("SUCCESS".equals(result.get("return_code")) && "SUCCESS".equals(result.get("result_code"))) {
                returnMap.put("trade_state", result.get("trade_state"));
                returnMap.put("total_fee", result.get("total_fee"));
                returnMap.put("fee_type", result.get("fee_type"));
                returnMap.put("cash_fee", result.get("cash_fee"));
                returnMap.put("transaction_id", result.get("transaction_id"));
                returnMap.put("out_trade_no", result.get("out_trade_no"));
                returnMap.put("attach", result.get("attach"));
                returnMap.put("time_end", result.get("time_end"));
                returnMap.put("trade_state_desc", result.get("trade_state_desc"));
                System.out.println("*************************="+ result.get("total_fee"));
                System.out.println("*************************="+ result.get("cash_fee"));
//                String orderIndexId = result.get("out_trade_no");
                if("SUCCESS".equals(result.get("trade_state"))){
                    resultBean=this.orderSuccess(orderIndexId,result.get("total_fee"));
                    returnMap.put("resultCode",resultBean.getResultCode());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnMap;
    }

    public synchronized ResultBean orderSuccess(String orderIndexId,String totalMoney){
        ResultBean resultBean = new ResultBean(ResultBean.FAIL);
        try {
            //totalMoney是以分为单位的
            CjOrderIndex orderIndex =cjOrderIndexRepository.findOne(orderIndexId);
            CjCustomer customer = cjCustomerRepository.findOne(orderIndex.getEmployeeId());
            List<CjPosition> positionList = cjPositionRepository.findByCustomerIdOrderByCreateTimeDesc(orderIndex.getEmployeeId());
            BigDecimal bigDecimal = orderIndex.getMoney().multiply(new BigDecimal(100));
            String str = bigDecimal.toString();
            double money = Double.parseDouble(str);//把钱转换为分为单位，并且不要小数点
            if(totalMoney.equals((int)money+"")){
                if(orderIndex != null && orderIndex.getPayStatus()==0){
                    orderIndex.setPayStatus(1);
                    cjOrderIndexRepository.saveAndFlush(orderIndex);
                    List<CjOrder> list = cjOrderRepository.findByOrderIndexId(orderIndexId);
                    if(list != null && list.size()>0){
                        //把云飞防商品数量加1
                        for(CjOrder order: list){
                            order.setPayStatus(1);//设置为支付状态
                            cjOrderRepository.saveAndFlush(order);
                            CjCommodityYun yuns=yunRepository.findOne(order.getYunId());
                            yuns.setScore(yuns.getScore()+1);
                            yunRepository.saveAndFlush(yuns);
                        }
                        //则需要分发给机手接单
                        //接单就需要客户积分和位置信息，指定位置的客户排名，只查询需要推送的
                        List<CjCustomer> lt = cjCustomerRepository.findByCountyAndIsDriverAuthAndRobotFlagAndIntegralNotNullOrderByIntegralDesc(positionList.get(0).getCounty(),true,0);
                        if(lt != null && lt.size()>0){
                            Thread thread = new Thread(new MyThreadRobot(smsRecordRepository,lt,list,cjTaskRepository,yunRepository,cjOrderDetailRepository,cjOrderRepository));
                            thread.start();
                        }
                    }
                    CjMoneyRecord moneyRecord1 = new CjMoneyRecord();
                    moneyRecord1.setMoney(orderIndex.getMoney());
                    moneyRecord1.setOrderId(orderIndexId);
                    moneyRecord1.setCustomerIncomeId("2c978b23752a450d01752aff74c8954g");//平台
                    moneyRecord1.setCustomerPayId(customer.getId());
                    moneyRecord1.setCreateDate(new Date());
                    moneyRecord1.setFettle(0);
                    moneyRecord1.setCustomerBelongId(customer.getId());
                    moneyRecord1.setName(customer.getCardName());
                    cjMoneyRecordRepository.saveAndFlush(moneyRecord1);
                    CjMoneyRecord moneyRecord2= new CjMoneyRecord();
                    moneyRecord2.setMoney(orderIndex.getMoney());
                    moneyRecord2.setOrderId(orderIndexId);
                    moneyRecord2.setCustomerIncomeId("2c978b23752a450d01752aff74c8954g");
                    moneyRecord2.setCustomerPayId(customer.getId());
                    moneyRecord2.setCreateDate(new Date());
                    moneyRecord2.setFettle(1);
                    moneyRecord2.setCustomerBelongId("2c978b23752a450d01752aff74c8954g");
                    moneyRecord2.setName("平台");
                    cjMoneyRecordRepository.saveAndFlush(moneyRecord2);
                    CjCustomer cjCustomer = cjCustomerRepository.findOne("2c978b23752a450d01752aff74c8954g");
                    cjCustomer.setMoney(cjCustomer.getMoney().add(moneyRecord2.getMoney()));
                    cjCustomerRepository.saveAndFlush(cjCustomer);
                    resultBean.setResultCode(ResultBean.SUCCESS);//走到这里才算做是成功
                }
            }else {
                AttackError attackError = new AttackError();
                attackError.setOrderIndexId(orderIndexId);
                attackError.setRealMoney(orderIndex.getMoney().toString());
                attackError.setErrorMoney(totalMoney);
                attackError.setCreateTime(new Date());
                attackErrorRepository.saveAndFlush(attackError);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultBean;
    }
}
